package com.qf.controller;

import com.qf.pojo.Order;
import com.qf.pojo.R;
import com.qf.service.UserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cloud.client.ServiceInstance;
import org.springframework.cloud.client.discovery.DiscoveryClient;
import org.springframework.cloud.client.loadbalancer.LoadBalancerClient;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.client.RestTemplate;

import javax.print.attribute.standard.PrinterURI;
import java.util.List;

//@RestController
//@RequestMapping("/user")
public class UserController {

    @Autowired
    UserService userService;

    @Autowired
    private RestTemplate restTemplate;

    @Autowired
    private DiscoveryClient discoveryClient;

    @Autowired
    private LoadBalancerClient loadBalancerClient;

    @GetMapping("/{id}")
    public R findOrders(@PathVariable("id") Integer id) throws InterruptedException {

        //发现服务
//        List<ServiceInstance> instances = discoveryClient.getInstances("qf-order");
//
//        ServiceInstance instance = instances.get(0);

        //基于负载均衡器选择一台提供者服务实例
        ServiceInstance instance = loadBalancerClient.choose("qf-order");
        int port = instance.getPort();
        String host = instance.getHost();

        R r = restTemplate.getForObject("http://"+host+":"+port+"/order/" + id, R.class);

        return r;
    }
}
